package dianmobile.eistarandroid.ui.fragments;

import android.app.Fragment;
import android.content.Intent;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
import android.widget.Toast;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import dianmobile.eistarandroid.R;
import dianmobile.eistarandroid.beans.MyArticleEntity;
import dianmobile.eistarandroid.network.request.MyArticleRequest;
import dianmobile.eistarandroid.network.request.RequestCallback;
import dianmobile.eistarandroid.ui.Adapter.MyArticleListAdapter;
import dianmobile.eistarandroid.ui.activities.ViewPostActivity;
import dianmobile.eistarandroid.utils.ConstantsData;
import zrc.widget.SimpleFooter;
import zrc.widget.SimpleHeader;
import zrc.widget.ZrcListView;

public class MyArticlesFragment extends Fragment {

    private ZrcListView myArticleListView;
    private TextView noArticleView;
    private MyArticleListAdapter myArticleListAdapter;
    private List<MyArticleEntity> listData = new ArrayList<>();
    private String startNum;
    private int lastStartNum;

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        return inflater.inflate(R.layout.fragment_my_articles, container, false);

    }
    @Override
    public void onActivityCreated(Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);

        myArticleListView = (ZrcListView)getActivity().findViewById(R.id.lv_my_articles_list);
        noArticleView = (TextView)getActivity().findViewById(R.id.tv_my_article_no_DATA);

        setPullToRefresh();

        myArticleListAdapter = new MyArticleListAdapter(getActivity(), listData);
        myArticleListView.setAdapter(myArticleListAdapter);
        refresh();

        myArticleListView.setOnItemClickListener(new ZrcListView.OnItemClickListener() {
            @Override
            public void onItemClick(ZrcListView parent, View view, int position, long id) {
                MyArticleEntity item = listData.get(position);
                Intent intent = new Intent(getActivity(), ViewPostActivity.class);
                intent.putExtra(ConstantsData.EXTRA_FILE_NAME, item.getFileName());
                intent.putExtra(ConstantsData.EXTRA_BOARD_NAME, item.getBoardName());
                getActivity().startActivity(intent);
            }
        });
    }

    /**
     * config the pull-to-refresh and load more at end
     */
    private void setPullToRefresh() {
        // 设置下拉刷新的样式（可选，但如果没有Header则无法下拉刷新）
        SimpleHeader header = new SimpleHeader(getActivity());
        header.setTextColor(0xff0066aa);
        header.setCircleColor(0xff33bbee);
        myArticleListView.setHeadable(header);

        SimpleFooter footer = new SimpleFooter(getActivity());
        footer.setCircleColor(0xff33bbee);
        myArticleListView.setFootable(footer);
        myArticleListView.startLoadMore();

        // 下拉刷新事件回调
        myArticleListView.setOnRefreshStartListener(new ZrcListView.OnStartListener() {
            @Override
            public void onStart() {
                refresh();
            }
        });

        myArticleListView.setOnLoadMoreStartListener(new ZrcListView.OnStartListener() {
            @Override
            public void onStart() {
                loadMore();
            }
        });
    }

    private void refresh() {
        Map<String, String> params = new HashMap<>();
        params.put(ConstantsData.EXTRA_START_NUM, "");
        params.put("lastStartNum", Integer.toString(100000));
        MyArticleRequest.execute(getActivity(), params, new RequestCallback() {
            @Override
            public void onResult(Map<String, Object> result, String error) {
                if (error == null) {
                    lastStartNum = (Integer) result.get(ConstantsData.EXTRA_START_NUM);
                    if (1 < lastStartNum) {
                        myArticleListView.startLoadMore();
                    }
                    listData.clear();
                    listData.addAll((ArrayList<MyArticleEntity>) result.get("result_data"));
                    myArticleListAdapter.notifyDataSetChanged();
                    if (listData.isEmpty()) {
                        noArticleView.setVisibility(View.VISIBLE);
                    } else {
                        noArticleView.setVisibility(View.INVISIBLE);
                    }
                    myArticleListView.setRefreshSuccess();
                } else {
                    myArticleListView.setRefreshFail("网络错误");
                }
            }
        });

    }

    private void loadMore() {
        Map<String, String> params = new HashMap<>();
        if (lastStartNum < 20) {
            params.put(ConstantsData.EXTRA_START_NUM, "0");
        } else {
            params.put(ConstantsData.EXTRA_START_NUM, Integer.toString(lastStartNum - 20));
        }
        params.put("lastStartNum", Integer.toString(lastStartNum));
        MyArticleRequest.execute(getActivity(), params, new RequestCallback() {
            @Override
            public void onResult(Map<String, Object> result, String error) {
                myArticleListView.setLoadMoreSuccess();
                if (error == null) {
                    lastStartNum = (Integer) result.get(ConstantsData.EXTRA_START_NUM); //更新startNum
                    if (0 >= lastStartNum) {
                        myArticleListView.stopLoadMore();
                    }
                    listData.addAll((ArrayList<MyArticleEntity>) result.get("result_data"));
                    myArticleListAdapter.notifyDataSetChanged();
                    if (listData.isEmpty()) {
                        myArticleListView.stopLoadMore();
                        noArticleView.setVisibility(View.VISIBLE);
                    } else {
                        noArticleView.setVisibility(View.INVISIBLE);
                    }
                } else {
                    Toast.makeText(getActivity(), "网络错误", Toast.LENGTH_SHORT).show();
                }
            }
        });
    }
}
